﻿using UnityEngine;

public class Floater : MonoBehaviour {
    public Vector3 offset;

    [Range(0.01f, 100f)]
    public float frequency;
    public bool playOnAwake;

    Vector3 _originPosition;
    float _tick;
    float _amplitude;
    bool _animate;

    void Awake() {
        // 如果没有设置频率或者设置的频率为0则自动记录成1
        if (Mathf.Approximately(frequency, 0))
            frequency = 1f;

        _originPosition = transform.localPosition;
        _tick = Random.Range(0f, 2f * Mathf.PI);
        _animate = playOnAwake;
    }

    public void Play() {
        transform.localPosition = _originPosition;
        _animate = true;
    }

    public void Stop() {
        transform.localPosition = _originPosition;
        _animate = false;
    }

    void FixedUpdate() {
        if (_animate) {
            // 计算振幅
            _amplitude = 2 * Mathf.PI / frequency;

            // 计算下一个时间量
            _tick = _tick + Time.fixedDeltaTime * _amplitude;

            // 计算下一个偏移量
            var amp = new Vector3(Mathf.Cos(_tick) * offset.x, Mathf.Sin(_tick) * offset.y, 0);

            transform.localPosition = _originPosition + amp;
        }
    }
}
